<template>
  <div>
    <el-dialog
      :title="eject.isadd == true ? '商品规格添加' : '商品规格编辑'"
      :visible.sync="eject.isshow"
      @closed="guanbi"
   
    >
      {{ form }}
      <el-form :model="form">
        <el-form-item label="一级分类" label-width="120px" :rules="rules">
          <el-select v-model="form.first_cateid" @change="change_first_cateid">
            <el-option value disabled>请选择</el-option>
            
            <el-option             
            v-for='item in catelist' 
            :key="item.id" 
            :label="item.catename"
            :value='item.id'
            ></el-option>
           
          </el-select>
        </el-form-item>

        <el-form-item label="二级分类" label-width="120px" :rules="rules">
          <el-select v-model="form.second_cateid">
            <el-option value disabled>请选择</el-option>
            <el-option 
            v-for="item in second_cate_list"
            :key="item.id"
            :value="item.id" 
            :label="item.catename"
            ></el-option>
            
          </el-select>
        </el-form-item>

        <el-form-item label="商品名称" label-width="120px" :rules="rules">
          <el-input
            v-model="form.goodsname"
            autocomplete="off"
            required
          ></el-input>
        </el-form-item>

        <el-form-item label="价格" label-width="120px" :rules="rules">
          <el-input v-model="form.price" autocomplete="off" required></el-input>
        </el-form-item>

        <el-form-item label="市场价格" label-width="120px" :rules="rules">
          <el-input
            v-model="form.market_price"
            autocomplete="off"
            required
          ></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px" :rules="rules">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"  />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- 商品规格 -->
        <el-form-item label="商品规格" label-width="120px" :rules="rules">
          <el-select v-model="form.specsid"
          @change="change_specs_id"
          >
            <el-option value disabled>请选择</el-option>
            <el-option 
            v-for="item in specslist"
            :key="item.id"
            :label="item.specsname"
            :value="item.id"
            ></el-option>
            
          </el-select>
        </el-form-item>

        <el-form-item label="商品属性" label-width="120px" :rules="rules">
          <el-select v-model="form.specsattr" multiple>
            <el-option label="请选择" value disabled></el-option>
            <el-option v-for="item in attrsArr" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        

        <el-form-item label="是否新品" label-width="120px" :rules="rules">
          <el-radio v-model="form.isnew" :label='1' >是</el-radio>
          <el-radio v-model="form.isnew" :label='2' >否</el-radio>
        </el-form-item>

        <el-form-item label="是否热卖" label-width="120px" :rules="rules">
          <el-radio v-model="form.ishot" :label='1' >是</el-radio>
          <el-radio v-model="form.ishot" :label='2' >否</el-radio>
        </el-form-item>

        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>

        <el-form-item label="商品描述" label-width="120px"> </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="add()" v-if="eject.isadd"
          >添 加</el-button
        >
        <el-button type="primary" @click="update" v-else>编 辑</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reqgoodsone, reqgoodsedit, reqgoodsadd,reqcatelist,reqspecslist } from "../../../request/api";
import { successAlert, errorAlert } from "../../../utils/alert";
import { mapActions, mapGetters } from "vuex";

export default {
  props: ["eject"],
  data() {
    return {
      radio: 1,
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: [],
        isnew: '2',
        ishot: '1',
        status: 1,
      },
      second_cate_list:[],
      //属性数组list
      attrsArr: [],
      // 存放规格属性的数组
      arrAttr: [
        {
          value: "",
        },
      ],
      rules: [
        {
          required: true,
        },
      ],
      imageUrl: "",
    };
  },
  created() {},
  mounted() {
    this.reqcatelist();
    this.resspecslist();
    
  },
  computed: {
    ...mapGetters({
      
      catelist:"cate/list",
      specslist:"specs/list"
    }),

  },
  methods: {

    //=============================================
    // change_specs_id(e){
  
    //       this.get_second_specs_list(e)
    // },
    // //获取2级属性list
    // get_second_specs_list(e){
    //   console.log(e);
    //         reqspecslist(e).then(res=>{
    //        console.log(res);
    // })
    // },
    //商品规格变了
    change_specs_id(e) {
      // form上的属性重置
      this.form.specsattr = [];
      console.log(e);
      this.get_attrs_arr(e);
    },
    get_attrs_arr(e) {
      // 计算规格属性list
      let obj =this.specslist.find((item)=>{
        return item.id == e
      })
      this.attrsArr = obj ? obj.attrs : []
      ;
     
    },
 //================================================
    // 以及分类change事件
    change_first_cateid(e){
      this.form.second_cateid = "";
         this.get_second_cate_list()
    },
      //获取2级分类list
    get_second_cate_list() {
      // 根据一级分类获取二级分类的list
      reqcatelist({ pid: this.form.first_cateid }).then((res) => {
        let list = res.data.list ? res.data.list : [];
        this.second_cate_list = list;
      });
    },

    addAttr() {
      this.arrAttr.push({ value: "" });
    },
    ...mapActions({
      resspecslist: "specs/reqlist",
      reqcatelist:"cate/reqlist",
      reslist:"goods/reqlist"
    }),

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg/png/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      this.form.img = file;
      this.imageUrl = URL.createObjectURL(file);
      return isJPG && isLt2M;
    },

    // 关闭弹框清楚样式清空表单
    guanbi() {
      !this.eject.isadd && this.empty();
    },

    // 点击取消告诉父组件关闭
    close() {
      this.$emit("close");
    },
    // 封装一个清空方法
    empty() {
      this.form = {
       
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: [],
        isnew: "",
        ishot: "",
        status: 1,
      };
      this.imageUrl= "",
      this.arrAttr = [
        {
          value: "",
        },
      ];
    },
    //点击添加按钮
    add() {
      // this.form.description = this.editor.txt.html();

      reqgoodsadd({...this.form,
      specsattr: this.form.specsattr.join(",")}
      ).then((res) => {
        // 添加成功之后
        if (res.data.code == 200) {
          // 弹出弹框
          successAlert(res.data.msg);
          // 清空输入框
          // this.empty();
          // 弹框消失
          this.eject.isshow = false;
          // 重新列表请求
          this.reslist();
        }
      });
    },
    update() {
      // 请求接口
      reqgoodsedit({
        ...this.form,
        specsattr: this.form.specsattr.join(","),
      }).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          // 弹出成功提示框
          successAlert(res.data.msg);
          // 清空输入框
          this.empty();
          // 关闭弹窗
          this.eject.isshow = false;
          // 通知仓库更新列表
          this.reslist();
          return;
        }
        if (res.data != 200) {
          errorAlert(res.data.msg);
        }
      });
    },

    // 获取一条信息方法，父组件通过ref调用
    getone(id) {
      reqgoodsone({ id: id }).then((res) => {
        console.log(res);

        if (res.data.code == 200) {
          this.form = res.data.list;
          //********************************* */
          this.form.id = id;
          this.get_second_cate_list();

          this.form.specsattr = this.form.specsattr.split(",");

          this.get_attrs_arr();
          this.imageUrl = this.$pre + this.form.img;
        }
      });
    },
  },
};
</script>

<style scoped  lang='less'>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.box {
  display: flex;
}
</style>
